package com.roc.web.action.merinfo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.bean.MerinfoChangeCheckBean;
import com.roc.bean.MerinfoChangeSearchVo;
import com.roc.bean.MerinfoDetail;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.AuditingItem;
import com.roc.pojo.MerinfoChange;
import com.roc.pojo.Operators;
import com.roc.pojo.TblEditMchtInf;
import com.roc.pojo.TblEditMchtPicture;
import com.roc.pojo.TblInsInf;
import com.roc.pojo.TblMchtInf;
import com.roc.service.IMerchantServices;
import com.roc.service.IMerinfoImageService;
import com.roc.service.ITerminalService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.merinfo.MerinfoChangeCheckService;
import com.roc.util.Constance;
import com.roc.util.Utils;
import com.roc.util.constant.AuditingResultCodeType;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.util.httpZip.HttpFileToZipUtil;

@Component
@Scope("prototype")
@Namespace("/merinfoChangeCheck")
@SuppressWarnings("unused")
public class MerinfoChangeCheckAction extends PaginationBaseAction{
    /**
	 * @Fields serialVersionUID : TODO
	 */
	    
	private static final long serialVersionUID = 1L;
	static Logger logger=Logger.getLogger(MerinfoChangeCheckAction.class);
	private MerinfoChangeCheckSearchCondition searchCondition;
	private List<TblInsInf> orgList=new ArrayList<TblInsInf>();
	private String[] agentList ;
	private TblMchtInf  merinfo; //商户信息表
	private MerinfoChange merinfoChange;//商户变更信息
	private TblEditMchtInf editMerinfo; // 商户临时表
	private MerinfoDetail merinfoDetail;//商户详情
	private AuditingItem auditing;//审核意见
	private List<MerinfoChangeSearchVo> merinfoSearchList = new ArrayList<MerinfoChangeSearchVo>();
	
	private String merInfoIdList;
	
	private InputStream zipFile;
	
	private String  zipName;
	
	@Autowired
	IorgService orgService;
	@Autowired
	IMerchantServices merinfoService;
	@Autowired
	IPageService pagenitionService;

	@Autowired
	ITerminalService terminalService; 
	
	@Autowired
	MerinfoChangeCheckService merinfoChangeCheckService;
	
	
	@Autowired
	IMerinfoImageService merinfoImageService;
	/**
	 * 下载 图片压缩包
	 * @Title: exportImageZip
	 * @Description: TODO
	 * @param @return    
	 * @return String    
	 * @throws
	 * @author jdd
	 */
	@Action(value="zipExportChange",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/octet-stream", "inputName",  
			            "zipFile","contentDisposition",  "attachment;filename=${zipName}.zip",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/pages/merinfo/merinfoChangeCheckDetail.jsp") }) 
	public String exportImageZip()
	{
		Operators op = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		
		List<String> urlList = new ArrayList<String>();
		List list = merinfoImageService.queryMerinfoChangImage(merinfo.getId());
		for (Object obj : list) {
			MerinfoChange pic = (MerinfoChange) obj;
			if(pic.getUrl1()!=null){  urlList.add(pic.getUrl1());   }
			if(pic.getUrl2()!=null){  urlList.add(pic.getUrl2());   }
			if(pic.getUrl3()!=null){  urlList.add(pic.getUrl3());   }
			if(pic.getUrl4()!=null){  urlList.add(pic.getUrl4());   }
			if(pic.getUrl5()!=null){  urlList.add(pic.getUrl5());   }
			if(pic.getUrl6()!=null){  urlList.add(pic.getUrl6());   }
			if(pic.getUrl7()!=null){  urlList.add(pic.getUrl7());   }
			if(pic.getUrl8()!=null){  urlList.add(pic.getUrl8());   }
			if(pic.getUrl9()!=null){  urlList.add(pic.getUrl9());   }
			if(pic.getUrl10()!=null){  urlList.add(pic.getUrl10());  }	
//			urlList.add("http://shoudan.freemypay.com:18090/fmposm/upload/showImg.ct?orgs=48502000&mid=85029000742000002001.jpg&time=1488346351602");

		}	
		
		String zipFilePath =Utils.getConfigValue("ZIP_FILE_PATH");//压缩包存放的文件夹
		boolean falg = HttpFileToZipUtil.httpFileToZip(zipFilePath, getZipName(), urlList.toArray());
		if(falg)
		{
			File file = new File(zipFilePath,getZipName()+".zip");
			try {
				zipFile = new FileInputStream(file);	
				HttpFileToZipUtil.deletefile(zipFilePath);	
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return ERROR;
			}
			return SUCCESS;
	
		}
		else 
			return ERROR;
	}
	/**
	 * 跳往商户复审页面,并加载下拉框的值
	 * @Title: init
	 * @Description:TODO(...)	 * @return
	 * @throws Exception
	 * @author jdd
	 * @date: 2016年12月24日 下午11:07:34
	 *
	 */
	@Action(value = "init", results = { @Result(name = "success", location = "/pages/merinfo/merinfoChangeCheck.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String init() {
		Operators op = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.AGENT.getCode()) && !op.getAccountNo().equals("sdsyb")){
			 addActionError("无权限访问");
			 return ERROR;
		 }
		try {
			//初始化机构
			orgList = orgService.queryOrgList();
		}catch (Exception e) {
			// TODO: handle exception
			addActionError("加载信息失败，请联系客服人员");
			logger.error(e.getMessage(),e);
		}
			
	   return SUCCESS;
    }
	
	/**
	 * 查询审核列表
	 * @Title: queryMerinfoCheck
	 * @Description:TODO(...)
	 * @return
	 * @throws Exception
	 * @author jdd
	 * @date: 2016年12月24日 下午11:00:18
	 *
	 */
	@Action(value = "queryMerinfoCheck", 
			results = { @Result(name = "success", location = "/pages/merinfo/merinfoChangeCheck.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String queryMerinfoCheck() {
		 Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		 if(op.getRoleType().equals(Role.AGENT.getCode()) && !op.getAccountNo().equals("sdsyb")){
			 addActionError("无权限访问");
			 return ERROR;
		 }
		
	         try {
	        	 init();
	        	 if(searchCondition==null){
						searchCondition=(MerinfoChangeCheckSearchCondition)getSearchConditionFromSession();
						if(searchCondition==null){
							searchCondition=new MerinfoChangeCheckSearchCondition();
						}
				}
						
				if(op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) || 
				    op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())  ){
					searchCondition.setOrgCode(op.getOrgCode());//当前查询人员所属收单机构
					searchCondition.setChangeFlag(4);//待审核状态
					searchCondition.setRoleId(op.getRoleType());// 角色
					searchCondition.setRkopId(String.valueOf(op.getId()));//操作员id
					    queryResultList();
						}
	         }catch (Exception e) {
				e.printStackTrace();
				logger.error(e.getMessage(), e);
				addActionError(e.getMessage());
				return ERROR;
			}
			return SUCCESS;
			
		}
	    /**
	     * 处理查询结果
	     */
	   
		   public void  queryResultList() throws Exception{
			try {
				 Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

				init();
				int rows=pagenitionService.countSQL(searchCondition);
				if(rows>0){
					searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				}
				List<MerinfoChangeCheckBean> msList=new ArrayList<MerinfoChangeCheckBean>();
				if(searchRsList.size()>0 && searchRsList!=null){
					
					Iterator iterator=searchRsList.iterator();
					while (iterator.hasNext()) {
						Object[] obj= (Object[])iterator.next();
						MerinfoChangeCheckBean  msb=new MerinfoChangeCheckBean(); 
	                    msb.setMid(Constance.Null2EmptyTrim(obj[0]));//商户号
	                    msb.setDealCode(Constance.Null2EmptyTrim(obj[1]));//商户变更类型
                        msb.setNameBusi(Constance.Null2EmptyTrim(obj[2]));//商户简称
                    	msb.setMerName(Constance.Null2EmptyTrim(obj[3]));
                    	msb.setStatus(Constance.Null2EmptyTrim(obj[4]));
                    	msb.setContactName(Constance.Null2EmptyTrim(obj[5])); 
                    	//msb.setContactPhoneno(Constance.Null2EmptyTrim(obj[6])); 
                    	String phone = Constance.Null2EmptyTrim(obj[6]);//手机号码
                    		 msb.setContactPhoneno(phone);//手机号
                    	msb.setCertif(Constance.Null2EmptyTrim(obj[7])); 
                    	//msb.setCertifNo(Constance.Null2EmptyTrim(obj[8]));
                    	String cardNo = Constance.Null2EmptyTrim(obj[8]); //法人代表证件号码
                    		 msb.setCertifNo(cardNo);//证件号
                    	msb.setAccountname(Constance.Null2EmptyTrim(obj[9])); 
                    	msb.setAccount(Constance.Null2EmptyTrim(obj[10])); 
                    	msb.setRegAddr(Constance.Null2EmptyTrim(obj[11])); 
                    	msb.setDtCreateTime(Constance.Null2EmptyTrim(obj[12])); 
                    	msb.setId(Long.parseLong(Constance.Null2EmptyTrim(obj[15]))); 
						msList.add(msb);
					}
				}
				this.setTotalPage(this.calcuTotalPage(rows));
				getRequest().setAttribute(SEARCH_RS_LIST, msList);
				getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
				getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
				setSearchToConditionSession(searchCondition);
				
			} catch (ServiceException e) {
				
				logger.error(e.getMessage(),e);
				addActionError(e.getMessage());
				
			}
		}
	
	
	/**
	 * 申请 信息 回显
	 * @Title: check
	 * @Description:TODO(...)
	 * @return
	 * @author jdd
	 * @date: 2016年12月25日 下午2:47:14
	 *
	 */
	@Action(value = "check", 
			results = { @Result(name = "success", location = "/pages/merinfo/merinfoChangeCheckDetail.jsp"),
			            @Result(name = "query", location = "/pages/merinfo/merinfoChangeCheck.jsp"),
			            @Result(name = "error", location = "/error.jsp")
    })
	public String check(){
	   Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try{
		
			if(merinfo.getId()==null ||  merinfo.getId().equals("")){
				addActionError("商户查询失败~！");
				return ERROR;
			}
			//查询商户信息
			merinfo = merinfoChangeCheckService.queryMerinfoDetailInfo(merinfo.getId(),true,op.getAgentType());
			//查询商户变更信息   
			merinfoChange=merinfoChangeCheckService.queryMerinfoChangeById(merinfo.getId());
			//查询历史驳回记录
			merinfoSearchList = merinfoChangeCheckService.queryMerinfoRejected(merinfo.getId());

			//审核意见
			Map<String,String> auditingMap=new HashMap<String, String>();
			auditingMap.put(AuditingResultCodeType.PASS.getCode(),AuditingResultCodeType.PASS.getName());
			auditingMap.put(AuditingResultCodeType.INCOMPLETE_INFO.getCode(),AuditingResultCodeType.INCOMPLETE_INFO.getName());
			getRequest().setAttribute("auditingMap",auditingMap);
			getRequest().setAttribute("merinf", merinfoChange);
			getRequest().setAttribute("merinfoSearchList",merinfoSearchList);
	       }catch (ServiceException e) {
			e.printStackTrace(); 
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}

	
	/**
	 * 审核
	 * @Title: checkAffir
	 * @Description:TODO(...)
	 * @return
	 * @throws Exception
	 * @author jdd
	 * @date: 2016年12月25日 下午2:22:48
	 *
	 */
	@Action(value = "checkAffir", 
			results = { @Result(name = "success", location = "/pages/merinfo/merinfoChangeCheck.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String checkAffir() {
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		if(auditing==null)
			return ERROR;
		try {
			
		
		if(StringUtils.isNotEmpty(auditing.getResult_code()))
		{
			if(StringUtils.isEmpty(merinfo.getId()))
				return ERROR;
			if(AuditingResultCodeType.PASS.getCode().equals(auditing.getResult_code()))
			{
				merinfoChange=merinfoChangeCheckService.queryMerinfoChangeById(merinfo.getId());
				
				merinfoChangeCheckService.checkChangePass(merinfoChange,op,auditing);
				addActionMessage("商户审核成功!");
			}else if(AuditingResultCodeType.INCOMPLETE_INFO.getCode().equals(auditing.getResult_code()))
			{
				//审核终止
				merinfoChangeCheckService.checkChangeShutDown(merinfo.getId(),op,auditing);
				addActionMessage("商户审核不通过!");
				//
			}else
				return ERROR;
			
		}else
			return ERROR;
		} catch (ServiceException e) {
			// TODO: handle exception
			e.printStackTrace(); 
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return init();
		
	}

	
	/**
	 * 跳转领件页面
	 * */
	@Action(value="collarPiecesChange",results={@Result(name=SUCCESS,location="/pages/merinfo/collarPiecesChange.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String returnCollarPiecesChange(){
		Operators loginOperators = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		if(loginOperators.getRoleType().equals(Role.AGENT.getCode()) && !loginOperators.getAccountNo().equals("sdsyb")){
			 addActionError("无权限访问");
			 return ERROR;
		 }
		try {
			//初始化机构
			orgList = orgService.queryOrgList();
		}catch (Exception e) {
			// TODO: handle exception
			addActionError("跳往领件页面错误");
			logger.error(e.getMessage(),e);
		}
			
	   return SUCCESS;
		
	}
	/**
	 *  变更资料风控领件	
	 * @Title: queryMerinfoCheckcollar
	 * @Description:TODO(...)
	 * @return
	 * @author jdd
	 * @date: 2017年1月4日 下午2:03:09
	 *
	 */
	@Action(value="queryCollarPiecesChange",
	results = { @Result(name = "success", location = "/pages/merinfo/collarPiecesChange.jsp"),
		@Result(name = "error", location = "/error.jsp")
})
	public String queryMerinfoCheckcollar(){
         Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
         if(op.getRoleType().equals(Role.AGENT.getCode()) && !op.getAccountNo().equals("sdsyb")){
			 addActionError("无权限访问");
			 return ERROR;
		 }
         try {
        	 init();
			
			//queryResultList();
			if(searchCondition==null){
					searchCondition=(MerinfoChangeCheckSearchCondition)getSearchConditionFromSession();
					if(searchCondition==null){
						searchCondition=new MerinfoChangeCheckSearchCondition();
					}
			}
			        searchCondition.setOrgCode(op.getOrgCode());//当前查询人员所属机构
					searchCondition.setChangeFlag(2);//领件查询
					searchCondition.setRoleId(op.getRoleType());// 角色
					searchCondition.setOpId(String.valueOf(op.getId()));//当前人员id
					if(op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) || 
					    op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())  ){
						    queryResultList();
	               }
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
		
	}
	
	@Action(value="saveCollarPiecesChange")
	public String saveCollarPiecesChange(){
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		PrintWriter pw = null;
		JSONObject json = new JSONObject();
		try {
			
			
			getResponse().setCharacterEncoding("utf-8");
			pw = getResponse().getWriter();
			
			logger.info(op.getRealName()+"开始领取商户,商户号是："+merInfoIdList);
			List<String> rsList = merinfoService.queryTChangeReceiveChange(op, merInfoIdList);
			
			json.put("rsList", rsList);
			pw.write(json.toString());
						
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			json.put("msg", "领取异常");
			/*json.put("boo", false);
			pw.write(json.toString());*/
		}finally{
			if(pw != null){
				pw.close();
			}
		}
		
		return null;
	}
	
	
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		// TODO Auto-generated method stub
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		// TODO Auto-generated method stub
		getSession().setAttribute(SEARCH_SESSION_BEAN_MERINFO_CHANGE_CHECK, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_BEAN_MERINFO_CHANGE_CHECK);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}

	public MerinfoChangeCheckSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(MerinfoChangeCheckSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public List<TblInsInf> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<TblInsInf> orgList) {
		this.orgList = orgList;
	}

	public String[] getAgentList() {
		return agentList;
	}

	public void setAgentList(String[] agentList) {
		this.agentList = agentList;
	}

	public TblMchtInf getMerinfo() {
		return merinfo;
	}

	public void setMerinfo(TblMchtInf merinfo) {
		this.merinfo = merinfo;
	}

	public MerinfoDetail getMerinfoDetail() {
		return merinfoDetail;
	}

	public void setMerinfoDetail(MerinfoDetail merinfoDetail) {
		this.merinfoDetail = merinfoDetail;
	}

	public AuditingItem getAuditing() {
		return auditing;
	}

	public void setAuditing(AuditingItem auditing) {
		this.auditing = auditing;
	}


	public MerinfoChange getMerinfoChange() {
		return merinfoChange;
	}


	public void setMerinfoChange(MerinfoChange merinfoChange) {
		this.merinfoChange = merinfoChange;
	}

	public TblEditMchtInf getEditMerinfo() {
		return editMerinfo;
	}

	public void setEditMerinfo(TblEditMchtInf editMerinfo) {
		this.editMerinfo = editMerinfo;
	}
	public InputStream getZipFile() {
		return zipFile;
	}
	public void setZipFile(InputStream zipFile) {
		this.zipFile = zipFile;
	}
	public String getZipName() {
		String zipName="商户图片"+Constance.formateDate();
		 
		try {
			zipName = new String(zipName.getBytes(),"ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			logger.info("生成图片名称失败了！");
		}
		return  zipName;
	}
	public void setZipName(String zipName) {
		this.zipName = zipName;
	}
	public String getMerInfoIdList() {
		return merInfoIdList;
	}
	public void setMerInfoIdList(String merInfoIdList) {
		this.merInfoIdList = merInfoIdList;
	}
	
	public List<MerinfoChangeSearchVo> getMerinfoSearchList() {
		return merinfoSearchList;
	}
	public void setMerinfoSearchList(List<MerinfoChangeSearchVo> merinfoSearchList) {
		this.merinfoSearchList = merinfoSearchList;
	}
	

}
